package com.jhy.new2025.BinaryTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * 层次遍历
 */
public class LevelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        ArrayDeque<TreeNode> deque = new ArrayDeque<>();
        if (root == null) {
            return res;
        }
        deque.offer(root);
        while (!deque.isEmpty()) {
            // 控制每一层的循环
            int size = deque.size();
            List<Integer> temp = new ArrayList<>();
            // 控制一层的循环
            while (size > 0) {
                TreeNode treeNode = deque.poll();
                temp.add(treeNode.val);
                if (treeNode.left != null) deque.offer(treeNode.left);
                if (treeNode.right != null) deque.offer(treeNode.right);
                size--;
            }
            res.add(temp);
        }
        return res;

    }

}
